#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ColRecSys - PyGTK Collection Record System
# Copyright (C) 2009 Bertrand Kintanar <b3rxkintanar@gmail.com>
# http://colrecsys.googlecode.com/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# If you find any bugs or have any suggestions email: b3rxkintanar@gmail.com
# URL: http://colrecsys.googlecode.com/
#
# ColRecSys needs the following to function properly:
#   python >= 2.5.1, gtk >= 2.12.9, pygtk >= 2.12.2,
#   sqlite >= 2.3.5, sqlalchemy >= 0.5.0

_ = lambda x : x

from config import *
from config import __appversion__

try:

    import base64
    import datetime
    import gettext
    import gobject
    import locale
    import os
    import pango
    import re
    import sys
    
except ImportError, e:

    print _("Import error %s cannot start:" % APP_NAME), e

    sys.exit(1)

try:

    import pygtk
    pygtk.require20()
    import gtk
    import gtk.glade

    try:

        assert gtk.ver >= (2, 14, 1)

    except AssertionError:

        print _("%s requires GTK+ 2.14.1 or higher, but %s was found") \
            % (APP_NAME, gtk.ver)

        sys.exit(1)

    if DEBUG:

        print _("Checking pygtk 2.0............. Found")
        print _("Checking gtk+ 2.14.1........... Found")
        print _("Checking glade................. Found")

except ImportError, e:

    print _("Import error %s cannot start:" % APP_NAME), e

    sys.exit(1)

from sql import *
from datepicker import CalendarEntry

session = checkDatabase('colrecsys.sqlite')
count = 0
total_undeposited = 0.0
current_date = None

"""Column IDs"""
COL_OBJECT      = 0
COL_OBJECT_TYPE = 1
COL_DATE        = 2
COL_ORNUM       = 3
COL_PAYOR       = 4
COL_NATURE      = 5
COL_AMOUNT      = 6
COL_PROV        = 7
COL_ZIP         = 8
COL_COUNTRY     = 9

class TVColumn(object):
    """This is a class that represents a column in the todo tree.
    It is simply a helper class that makes it easier to inialize the
    tree."""

    def __init__(self, ID, type, name, pos, visible=False, cellrenderer = None):
        """
        @param ID - int - The Columns ID
        @param type - int  - A gobject.TYPE_ for the gtk.TreeStore
        @param name - string - The name of the column
        @param pos - int - The index of the column.
        @param visible - boolean - Is the column visible or not?
        @param cellrenderer - gtk.CellRenderer - a constructor function
        for the column
        """
        self.ID = ID
        self.type = type
        self.name = name
        self.pos = pos
        self.visible = visible
        self.cellrenderer = cellrenderer
        self.colour = 0

    def __str__(self):

        return "<TVColumn object: ID = %s type = %s name = %s pos = %d visible = %s cellrenderer = %s>" % (self.ID, self.type, self.name, self.pos, self.visible, self.cellrenderer)

class ColRecSys(object):
    
    def __init__(self):
        
        if DEBUG:
            
            print _("Initializing"), APP_NAME
            
        #Get the local path
        self.local_path = os.path.realpath(os.path.dirname(sys.argv[0]))
        #Translation stuff
        self.initialize_translation()
        self.initialize_locale()
        
        #Set the Glade file
        self.gladefile = os.path.join(self.local_path, "glade", "colrecsys.glade")
        
        #Get the Main Widget Tree
        self.wTree = gtk.glade.XML(self.gladefile, "mainWindow")
        self.main_window = self.wTree.get_widget("mainWindow")
        
        #Initialize some widgets
        self.initialize_widgets()
        
        if LOGIN:
            
            self.security()
            self.set_permissions()
            
        self.main_window.set_title(APP_NAME + " " + __appversion__)
        self.main_window.maximize()
        
        #Connect with yourself
        self.wTree.signal_autoconnect(self)
        
        self.trPayorEntry.grab_focus()
        self.main_window.show_all()
        
    #***************************************************************************
    # Initialize
    #***************************************************************************
    def initialize_widgets(self):

        self.notebook    = self.wTree.get_widget("notebook")
        self.root_window = self.main_window.get_root_window()

        self.create_buttonImages()
        self.create_statusbar()
        self.create_aboutDialog()
        self.create_maintenaceDialog()
        self.create_trWidgets()
        self.create_reWidgets()
        self.create_trDialog()
        
    def initialize_locale(self):
        
        loc = ('English_Republic of the Philippines', '1252')
        locale.setlocale(locale.LC_ALL, loc)
        
    def initialize_translation(self):
        """This function initializes the possible translations"""

        # Init the list of languages to support
        langs = []

        #Check the default locale
        lc, encoding = locale.getdefaultlocale()

        if (lc):
            #If we have a default, it's the first in the list
            langs = [lc]

        # Now lets get all of the supported languages on the system
        language = os.environ.get('LANGUAGE', None)

        if (language):
            """
            language comes back something like en_CA:en_US:en_GB:en
            on linuxy systems, on Win32 it's nothing, so we need to
            split it up into a list
            """

            langs += language.split(":")

        """
        Now add on to the back of the list the translations that we
        know that we have, our defaults
        """

        langs += ["en_CA", "en_US", "tl_PH"]

        """
        Now langs is a list of all of the languages that we are going
        to try to use.  First we check the default, then what the system
        told us, and finally the 'known' list
        """

        gettext.bindtextdomain(APP_NAME, self.local_path)
        gettext.textdomain(APP_NAME)

        # Get the language to use
        self.lang = gettext.translation(APP_NAME, self.local_path
                                        , languages=langs, fallback = True)

        """
        Install the language, map _() (which we marked our
        strings to translate with) to self.lang.gettext() which will
        translate them.
        """
        gettext.install(APP_NAME, self.local_path)

    #***************************************************************************
    # Create Widgets
    #***************************************************************************
    def create_buttonImages(self):

        self.trButton = self.wTree.get_widget("trButton")
        self.reButton = self.wTree.get_widget("reButton")
        self.daButton = self.wTree.get_widget("daButton")
        self.maButton = self.wTree.get_widget("maButton")

        trImageBox = self.add_image(self, "transactions_48x48.png", _("T_ransactions"))
        reImageBox = self.add_image(self, "reports_48x48.png", _("Rep_orts"))
        maImageBox = self.add_image(self, "maintenance_48x48.png", _("_Maintenance"))
        daImageBox = self.add_image(self, "dayend_48x48.png", _("Day-_End"))

        self.trButton.set_image(trImageBox)
        self.reButton.set_image(reImageBox)
        self.maButton.set_image(maImageBox)
        self.daButton.set_image(daImageBox)
        
        trImageBox.show()
        reImageBox.show()
        maImageBox.show()
        daImageBox.show()
        
        if DEBUG:
            
            print _("   Creating buttonImages....... Done")
            
    def create_statusbar(self):
        
        self.statusbar = self.wTree.get_widget("statusbar")
        
        self.context_id = self.statusbar.get_context_id("ColRecSys")
        self.statusbar.push(self.context_id, _("Welcome to %s %s") \
            % (APP_NAME, __appversion__))
        
        if DEBUG:
            
            print _("   Creating statusbar.......... Done")
            
    def create_aboutDialog(self):

        #load the dialog from the glade file
        wTree = gtk.glade.XML(self.gladefile, "aboutDialog")

        #Get the actual dialog widget
        self.aboutDialog = wTree.get_widget("aboutDialog")
        #self.aboutDialog.set_icon()

        if DEBUG:

            print _("   Creating aboutDialog........ Done")

    def create_maintenaceDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "maintenanceDialog")
        self.maintenanceDialog = wTree.get_widget("maintenanceDialog")
        self.maNotebook = wTree.get_widget("maNotebook")
        self.maTreeview = wTree.get_widget("maTreeview")
        
        self.create_maListstore()
        
        wTree.signal_autoconnect(self)
        
    def create_trWidgets(self):
        
        self.trCollectionStringList = []
        
        self.trPayorEntry   = self.wTree.get_widget("trPayorEntry")
        self.trOREntry      = self.wTree.get_widget("trOREntry")
        self.trDateCalendar = CalendarEntry('')
        self.trCoEntry      = self.wTree.get_widget("trCoEntry")
        
        self.trPayorLabel   = self.wTree.get_widget("trPayorLabel")
        self.trORLabel      = self.wTree.get_widget("trORLabel")
        self.trDateLabel    = self.wTree.get_widget("trDateLabel")
        self.trCoLabel      = self.wTree.get_widget("trCoLabel")
        
        self.trDateTable    = self.wTree.get_widget("trDateTable")
        
        # set trDateLabel's mnemonic widget to button of trDateCalendar.
        self.trDateLabel.set_mnemonic_widget(self.trDateCalendar.button)
        
        # attach trDateCalendar to trDateTable and show.
        self.trDateTable.attach(self.trDateCalendar, 1, 2 , 0, 1)
        self.trDateCalendar.show_all()
        
        self.trWidgets = \
            [
                [self.trPayorEntry, self.trPayorLabel, self.trPayorLabel.get_label(), 0],
                [self.trOREntry, self.trORLabel, self.trORLabel.get_label(), 0],
                [self.trCoEntry, self.trCoLabel, self.trCoLabel.get_label(), 0]
            ]
        
        trCoListstore  = gtk.ListStore(str)
        self.trCoCompletion = gtk.EntryCompletion()
        
        li = [] # Populate the trCoListstore with data from database.
        for instance in session.query(Particular).order_by(Particular.name):
            
            if instance.name not in li:
                trCoListstore.append([instance.name])
                li.append(instance.name)
                
        self.trCoCompletion.set_model(trCoListstore)
        self.trCoEntry.set_completion(self.trCoCompletion)
        self.trCoCompletion.set_text_column(0)
        
        if DEBUG:
            
            print _("   Creating trWidgets.......... Done")
            
        self.create_trCoListstore()
        self.create_trBuDialog()
        self.create_trAcDialog()
        self.create_trPrDialog()
        self.create_trReDialog()
        self.create_trFiDialog()
        self.create_trDeDialog()
        self.create_trPeDialog()
        
    def create_reWidgets(self):
        
        self.reFilterCombobox  = self.wTree.get_widget("reFilterCombobox")
        self.reFromDateLabel   = self.wTree.get_widget("reFromDateLabel")
        self.reToDateLabel   = self.wTree.get_widget("reToDateLabel")
        
        self.reFindButton = self.wTree.get_widget("reFindButton")
        self.rePrintButton = self.wTree.get_widget("rePrintButton")
        
        self.reFilterListstore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.reFilterCombobox.pack_start(cellRenderer, True)
        self.reFilterCombobox.add_attribute(cellRenderer, 'text', 0)
        
        self.reFromDateCalendar = CalendarEntry('')
        self.reToDateCalendar   = CalendarEntry('')
        
        li = [_("Commission on Audit"), _("Bureau of Internal Revenue"), 
              _("Department of Trade and Industry")]
        
        for item in li:
            
            self.reFilterListstore.append([item])
            
        self.reFilterCombobox.set_model(self.reFilterListstore)
        self.reFilterCombobox.set_active(0)
        
        self.reFromDateTable = self.wTree.get_widget("reFromDateTable")
        self.reToDateTable   = self.wTree.get_widget("reToDateTable")
        
        # set reFromDateCalendar's date to a week ago.
        week = datetime.timedelta(days=7)
        self.reFromDateCalendar.set_date(datetime.date.today() - week)
        
        # set reFromDateLabel's mnemonic widget to button of reFromDateCalendar.
        self.reFromDateLabel.set_mnemonic_widget(self.reFromDateCalendar.button)
        # set reToDateLabel's mnemonic widget to button of reToDateCalendar.
        self.reToDateLabel.set_mnemonic_widget(self.reToDateCalendar.button)
        
        # attach reFromDateCalendar to reFromDateTable and show.
        self.reFromDateTable.attach(self.reFromDateCalendar, 1, 2 , 0, 1)
        self.reFromDateCalendar.show_all()
        
        # attach reToDateCalendar to reToDateTable and show.
        self.reToDateTable.attach(self.reToDateCalendar, 1, 2 , 0, 1)
        self.reToDateCalendar.show_all()
        
        if DEBUG:
            
            print _("   Creating reWidgets.......... Done")
            
        self.create_reCOAListstore()
            
    def create_trCoListstore(self):

        self.trCoListstore_columns = [
              TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_DATE, gobject.TYPE_STRING, _("Date"), 2, True, gtk.CellRendererText())
            , TVColumn(COL_ORNUM, gobject.TYPE_STRING, _("OR / DS #"), 3, True, gtk.CellRendererText())
            , TVColumn(COL_PAYOR, gobject.TYPE_STRING, _("Payor"), 4, True, gtk.CellRendererText())
            , TVColumn(COL_NATURE, gobject.TYPE_STRING, _("Nature of Collection"), 5, True, gtk.CellRendererText())
            , TVColumn(COL_AMOUNT, gobject.TYPE_STRING, _("Amount"), 6, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__trCo_column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.trCoTreeview = self.wTree.get_widget("trCoTreeview")
        #Make it so that the colours of each row can alternate
        self.trCoTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.trCoListstore_columns:
            #Add the column to the column dict
            self.__trCo_column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                if item_column.name == _("Amount") or item_column.name == _("OR / DS #"):
                    
                    item_column.cellrenderer.set_property('xalign', 1)
                    column.set_alignment(1)
                    
                # Set the column to expand if it is the column Title
                column.set_expand(item_column.name == _("Nature of Collection"))
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.trCoTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.trCoListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.trCoTreeview.set_model(self.trCoListstore)
        
        if DEBUG:
            
            print _("   Creating trCoListstore...... Done")
            
        self.populate_trListstore()
        
    def create_reCOAListstore(self):
        
        self.reCOAListstore_columns = [
              TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_DATE, gobject.TYPE_STRING, _("Date"), 2, True, gtk.CellRendererText())
            , TVColumn(COL_ORNUM, gobject.TYPE_STRING, _("OR / DS #"), 3, True, gtk.CellRendererText())
            , TVColumn(COL_PAYOR, gobject.TYPE_STRING, _("Payor"), 4, True, gtk.CellRendererText())
            , TVColumn(COL_NATURE, gobject.TYPE_STRING, _("Nature of Collection"), 5, True, gtk.CellRendererText())
            , TVColumn(COL_AMOUNT, gobject.TYPE_STRING, _("Amount"), 6, True, gtk.CellRendererText())
        ]

        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__reCOA_column_dict = {} #For easy access later on

        #Get the treeView from the widget Tree
        self.reCOATreeview = self.wTree.get_widget("reCOATreeview")
        #Make it so that the colours of each row can alternate
        self.reCOATreeview.set_rules_hint(True)

        # Loop through the columns and initialize the Tree
        for item_column in self.reCOAListstore_columns:
            #Add the column to the column dict
            self.__reCOA_column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):

                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)

                if item_column.name == _("Amount") or item_column.name == _("OR / DS #"):

                    item_column.cellrenderer.set_property('xalign', 1)
                    column.set_alignment(1)

                # Set the column to expand if it is the column Title
                column.set_expand(item_column.name == _("Nature of Collection"))

                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.reCOATreeview.append_column(column)

        #Create the gtk.TreeStore Model to use with the inTreeview
        self.reCOAListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.reCOATreeview.set_model(self.reCOAListstore)
        
        if DEBUG:
            
            print _("   Creating reCOAListstore..... Done")
            
    def create_maListstore(self):
        
        self.maListstore_columns = [
              TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_DATE, gobject.TYPE_STRING, _("Title"), 2, True, gtk.CellRendererText())
        ]

        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__ma_column_dict = {} #For easy access later on

        #Get the treeView from the widget Tree
        #self.reCOATreeview = self.wTree.get_widget("reCOATreeview")
        #Make it so that the colours of each row can alternate
        self.maTreeview.set_rules_hint(False)
        self.maTreeview.set_headers_visible(False)

        # Loop through the columns and initialize the Tree
        for item_column in self.maListstore_columns:
            #Add the column to the column dict
            self.__ma_column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):

                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)

                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.maTreeview.append_column(column)

        #Create the gtk.TreeStore Model to use with the inTreeview
        self.maListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.maTreeview.set_model(self.maListstore)
        
        if DEBUG:
            
            print _("   Creating maListstore........ Done")
            
        self.populate_maListstore()
    def create_trBuDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trBuDialog")
        
        self.trBuDialog = wTree.get_widget("trBuDialog")
        self.trBuGeneralTable = wTree.get_widget("trBuGeneralTable")
        
        self.trBuRegCheckButton       = wTree.get_widget("trBuRegCheckButton")
        self.trBuNewRadioButton       = wTree.get_widget("trBuNewRadioButton")
        self.trBuRenewalRadioButton   = wTree.get_widget("trBuRenewalRadioButton")
        self.trBuDocStampsCheckButton = wTree.get_widget("trBuDocStampsCheckButton")
        self.trBuSurchargeCheckButton = wTree.get_widget("trBuSurchargeCheckButton")
        self.trBuCertificationCheckButton = wTree.get_widget("trBuCertificationCheckButton")
        self.trBuChangeOfBNCheckButton = wTree.get_widget("trBuChangeOfBNCheckButton")
        self.trBuBulkCheckButton = wTree.get_widget("trBuBulkCheckButton")
        
        self.trBuNewLabel     = wTree.get_widget("trBuNewLabel")
        self.trBuRenewalLabel = wTree.get_widget("trBuRenewalLabel")
        self.trBuDocStampsLabel = wTree.get_widget("trBuDocStampsLabel")
        self.trBuSurchargeLabel = wTree.get_widget("trBuSurchargeLabel")
        self.trBuCertificationLabel = wTree.get_widget("trBuCertificationLabel")
        self.trBuChangeOfBNLabel = wTree.get_widget("trBuChangeOfBNLabel")
        self.trBuBulkLabel = wTree.get_widget("trBuBulkLabel")
        self.trBuTotalTextLabel = wTree.get_widget("trBuTotalTextLabel")
        self.trBuTotalLabel = wTree.get_widget("trBuTotalLabel")
        
        self.trBuOKButton = wTree.get_widget("trBuOKButton")
        
        self.trBuWidgets = \
            [
                [self.trBuNewRadioButton, self.trBuNewLabel],
                [self.trBuRenewalRadioButton, self.trBuRenewalLabel],
                [self.trBuDocStampsCheckButton, self.trBuDocStampsLabel],
                [self.trBuSurchargeCheckButton, self.trBuSurchargeLabel],
                [self.trBuCertificationCheckButton, self.trBuCertificationLabel],
                [self.trBuChangeOfBNCheckButton, self.trBuChangeOfBNLabel],
                [self.trBuBulkCheckButton, self.trBuBulkLabel],
                [self.trBuTotalTextLabel, self.trBuTotalLabel],
            ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trBuWidgets:
            
            size_group.add_widget(widget[1])
            
        di = {
            self.trBuNewRadioButton.get_label().replace("_", ""):self.trBuNewLabel,
            self.trBuRenewalRadioButton.get_label().replace("_", ""):self.trBuRenewalLabel,
            self.trBuDocStampsCheckButton.get_label().replace("_", ""):self.trBuDocStampsLabel,
            self.trBuSurchargeCheckButton.get_label().replace("_", ""):self.trBuSurchargeLabel,
            self.trBuCertificationCheckButton.get_label().replace("_", ""):self.trBuCertificationLabel,
            self.trBuChangeOfBNCheckButton.get_label().replace("_", ""):self.trBuChangeOfBNLabel,
            self.trBuBulkCheckButton.get_label().replace("_", ""):self.trBuBulkLabel,
        }
        
        self.trBuTotal = 0.0
        for instance in session.query(Particular).\
            filter(Particular.name=="BN Registration"):
            
            di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
            
            if instance.description == "New" or instance.description == "Documentary Stamps":
                
                self.trBuTotal  += instance.cost
            
        display_total = "<b>%s</b>" % locale.currency(self.trBuTotal, grouping=True)
        self.trBuTotalLabel.set_label(display_total)
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trBuDialog......... Done")
            
    def create_trAcDialog(self):
        
        wtree = gtk.glade.XML(self.gladefile, "trAcDialog")
        
        self.trAcDialog = wtree.get_widget("trAcDialog")
        
        self.trAcStarCombobox = wtree.get_widget("trAcStarCombobox")
        self.trAcFilingCheckButton = wtree.get_widget("trAcFilingCheckButton")
        self.trAcSurchargeCheckButton = wtree.get_widget("trAcSurchargeCheckButton")
        
        self.trAcStarLabel      = wtree.get_widget("trAcStarLabel")
        self.trAcFilingLabel    = wtree.get_widget("trAcFilingLabel")
        self.trAcSurchargeLabel = wtree.get_widget("trAcSurchargeLabel")
        self.trAcTotalLabel     = wtree.get_widget("trAcTotalLabel")
        self.trAcTotalTextLabel = wtree.get_widget("trAcTotalTextLabel")
        
        self.trAcStarListStore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.trAcStarCombobox.pack_start(cellRenderer, True)
        self.trAcStarCombobox.add_attribute(cellRenderer, 'text', 0)
        
        for p in session.query(Particular).filter(Particular.name=="Accreditation Fee"):
             
            if "Star" in p.description:
                
                self.trAcStarListStore.append([p.description])
                
        self.trAcStarCombobox.set_model(self.trAcStarListStore)
        self.trAcStarCombobox.set_active(0)
        
        p = session.query(Particular).filter(Particular.name=="Accreditation Fee").\
          filter(Particular.description=="1 Star").one()
        
        self.trAcStarLabel.set_label(locale.currency(p.cost, grouping=True))
        self.AccredTotal = p.cost
        
        self.trAccedWidget = \
            [
                [self.trAcStarCombobox, self.trAcStarLabel],
                [self.trAcFilingCheckButton, self.trAcFilingLabel],
                [self.trAcSurchargeCheckButton, self.trAcSurchargeLabel],
                [self.trAcTotalTextLabel, self.trAcTotalLabel],
            ]
        
        di = {
            "Filing Fees":self.trAcFilingLabel,
            "Surcharge Fees":self.trAcSurchargeLabel,
            "Documentary Stamps":self.trBuDocStampsLabel,
        }
        
        for instance in session.query(Particular).\
            filter(Particular.name=="Accreditation Fee"):
            
            if "Star" not in instance.description:
                
                di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
                
        self.trAcSurchargeLabel.set_label(locale.currency(self.AccredTotal * .5, grouping=True))
        
        display_total = "<b>%s</b>" % locale.currency(self.AccredTotal, grouping=True)
        self.trAcTotalLabel.set_label(display_total)
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trAccedWidget:
            
            size_group.add_widget(widget[1])
            
        wtree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trAcDialog......... Done")
            
    def create_trPrDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trPrDialog")
        
        self.trPrDialog = wTree.get_widget("trPrDialog")
        
        self.trPrOneRadioButton = wTree.get_widget("trPrOneRadioButton")
        self.trPrSeveralRadioButton = wTree.get_widget("trPrSeveralRadioButton")
        self.trPrTwoRadioButton = wTree.get_widget("trPrTwoRadioButton")
        
        self.trPrOneLabel = wTree.get_widget("trPrOneLabel")
        self.trPrSeveralLabel = wTree.get_widget("trPrSeveralLabel")
        self.trPrTwoLabel = wTree.get_widget("trPrTwoLabel")
        
        self.trPrTotalTextLabel = wTree.get_widget("trPrTotalTextLabel")
        self.trPrTotalLabel = wTree.get_widget("trPrTotalLabel")
        
        self.trPrWidgets = \
            [
                [self.trPrOneRadioButton, self.trPrOneLabel],
                [self.trPrSeveralRadioButton, self.trPrSeveralLabel],
                [self.trPrTwoRadioButton, self.trPrTwoLabel],
            ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trPrWidgets:
            
            size_group.add_widget(widget[1])
            
            
        di = {
            self.trPrOneRadioButton.get_label().replace("_", ""):self.trPrOneLabel,
            self.trPrSeveralRadioButton.get_label().replace("_", ""):self.trPrSeveralLabel,
            self.trPrTwoRadioButton.get_label().replace("_", ""):self.trPrTwoLabel,
        }
        
        for instance in session.query(Particular).\
            filter(Particular.name=="Sales Promo"):
            
            di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
            
        p = session.query(Particular).filter(Particular.name=="Sales Promo").\
          filter(Particular.description=="One Province").one()
        
        self.trPrOneRadioButton.set_active(True)
            
        self.PromoTotal = p.cost
        display_total = "<b>%s</b>" % locale.currency(self.PromoTotal, grouping=True)
        self.trPrTotalLabel.set_label(display_total)
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trPrDialog......... Done")
            
    def create_trReDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trReDialog")
        
        self.trReDialog = wTree.get_widget("trReDialog")
        self.trReExamRadioButton = wTree.get_widget("trReExamRadioButton")
        self.trReSalesmanRadioButton = wTree.get_widget("trReSalesmanRadioButton")
        self.trReAppraiserRadioButton = wTree.get_widget("trReAppraiserRadioButton")
        self.trReBrokerRadioButton = wTree.get_widget("trReBrokerRadioButton")
        self.trReConsultantRadioButton = wTree.get_widget("trReConsultantRadioButton")
        self.trReSurchargeCheckButton = wTree.get_widget("trReSurchargeCheckButton")
        
        self.trReExamLabel = wTree.get_widget("trReExamLabel")
        self.trReSalesmanLabel = wTree.get_widget("trReSalesmanLabel")
        self.trReAppraiserLabel = wTree.get_widget("trReAppraiserLabel")
        self.trReBrokerLabel = wTree.get_widget("trReBrokerLabel")
        self.trReConsultantLabel = wTree.get_widget("trReConsultantLabel")
        self.trReSurchargeLabel = wTree.get_widget("trReSurchargeLabel")
        
        self.trReTotalTextLabel = wTree.get_widget("trReTotalTextLabel")
        self.trReTotalLabel = wTree.get_widget("trReTotalLabel")
        
        self.trReCollection = ""
        self.has_surcharge  = False
        
        self.trReWidgets = \
            [
                [self.trReExamRadioButton, self.trReExamLabel],
                [self.trReSalesmanRadioButton, self.trReSalesmanLabel],
                [self.trReAppraiserRadioButton, self.trReAppraiserLabel],
                [self.trReBrokerRadioButton, self.trReBrokerLabel],
                [self.trReConsultantRadioButton, self.trReConsultantLabel],
                [self.trReSurchargeCheckButton, self.trReSurchargeLabel],
            ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trReWidgets:
            
            size_group.add_widget(widget[1])
            
        di = {
            self.trReExamRadioButton.get_label().replace("_", ""):self.trReExamLabel,
            self.trReSalesmanRadioButton.get_label().replace("_", ""):self.trReSalesmanLabel,
            self.trReAppraiserRadioButton.get_label().replace("_", ""):self.trReAppraiserLabel,
            self.trReBrokerRadioButton.get_label().replace("_", ""):self.trReBrokerLabel,
            self.trReConsultantRadioButton.get_label().replace("_", ""):self.trReConsultantLabel,
            self.trReSurchargeCheckButton.get_label().replace("_", ""):self.trReSurchargeLabel,
        }
        
        for instance in session.query(Particular).\
            filter(Particular.name=="Real Estate"):
            
            if instance.description == self.trReExamRadioButton.get_label().replace("_", ""):
                
                di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
                
            else:
                
                di[instance.description].set_label(locale.currency(instance.cost * 3, grouping=True))
            
        p = session.query(Particular).filter(Particular.name=="Real Estate").\
          filter(Particular.description=="Exam Fee").one()
        
        self.trReExamRadioButton.set_active(True)
            
        self.trReTotal = p.cost
        display_total = "<b>%s</b>" % locale.currency(self.trReTotal, grouping=True)
        self.trReTotalLabel.set_label(display_total)
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trReDialog......... Done")
            
    def create_trFiDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trFiDialog")
        
        self.trFiDialog = wTree.get_widget("trFiDialog")
        
        self.trFiWholesalerRadioButton = wTree.get_widget("trFiWholesalerRadioButton")
        self.trFiRetailerRadioButton = wTree.get_widget("trFiRetailerRadioButton")
        self.trFiSalesmanRadioButton = wTree.get_widget("trFiSalesmanRadioButton")
        
        self.trFiWholesalerLabel = wTree.get_widget("trFiWholesalerLabel")
        self.trFiRetailerLabel = wTree.get_widget("trFiRetailerLabel")
        self.trFiSalesmanLabel = wTree.get_widget("trFiSalesmanLabel")
        
        self.trFiTotalTextLabel = wTree.get_widget("trFiTotalTextLabel")
        self.trFiTotalLabel = wTree.get_widget("trFiTotalLabel")
        
        self.trFiWidgets = \
            [
                [self.trFiWholesalerRadioButton, self.trFiWholesalerLabel],
                [self.trFiRetailerRadioButton, self.trFiRetailerLabel],
                [self.trFiSalesmanRadioButton, self.trFiSalesmanLabel],
            ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trFiWidgets:
            
            size_group.add_widget(widget[1])
            
        di = {
            self.trFiWholesalerRadioButton.get_label().replace("_", ""):self.trFiWholesalerLabel,
            self.trFiRetailerRadioButton.get_label().replace("_", ""):self.trFiRetailerLabel,
            self.trFiSalesmanRadioButton.get_label().replace("_", ""):self.trFiSalesmanLabel,
        }
        
        for instance in session.query(Particular).\
            filter(Particular.name=="Fire Extinguisher"):
            
            di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
            
        p = session.query(Particular).filter(Particular.name=="Fire Extinguisher").\
          filter(Particular.description=="Wholesaler").one()
        
        self.trFiWholesalerRadioButton.set_active(True)
            
        self.trFiTotal = p.cost
        display_total = "<b>%s</b>" % locale.currency(self.trFiTotal)
        self.trFiTotalLabel.set_label(display_total)
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trFiDialog......... Done")
            
    def create_trDeDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trDeDialog")
        
        self.trDeDialog = wTree.get_widget("trDeDialog")
        
        self.trDeBIRRadioButton = wTree.get_widget("trDeBIRRadioButton")
        self.trDeDTIRadioButton = wTree.get_widget("trDeDTIRadioButton")
        
        self.trDeBIRSpinbutton  = wTree.get_widget("trDeBIRSpinbutton")
        self.trDeDTISpinbutton  = wTree.get_widget("trDeDTISpinbutton")
        
        self.trDeTotalLabel     = wTree.get_widget("trDeTotalLabel")
        
        self.trDeDTICurSymLabel = wTree.get_widget("trDeDTICurSymLabel")
        self.trDeBIRCurSymLabel = wTree.get_widget("trDeBIRCurSymLabel")
        
        self.trDeOKButton       = wTree.get_widget("trDeOKButton")
        
        self.trDeDTICurSymLabel.set_label(locale.localeconv().values()[12])
        self.trDeBIRCurSymLabel.set_label(locale.localeconv().values()[12])
        
        self.trDeTotal = 0.0
        self.trDeAccount = self.trDeBIRRadioButton.get_label().replace("_", "")
        display_total = "<b>%s</b>" % locale.currency(self.trDeTotal, grouping=True)
        self.trDeTotalLabel.set_label(display_total)
        
        self.trDeWidgets = \
            [
                [self.trDeBIRRadioButton, self.trDeBIRSpinbutton],
                [self.trDeDTIRadioButton, self.trDeDTISpinbutton],
            ]
        
        self.on_trDeRadioButton_toggled(self.trDeDTIRadioButton)
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trDeWidgets:
            
            size_group.add_widget(widget[1])
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trDeDialog......... Done")
        
    def create_trPeDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trPeDialog")
        
        self.trPeDialog = wTree.get_widget("trPeDialog")
        
        self.trPeAssessmentCheckButton = wTree.get_widget("trPeAssessmentCheckButton")
        self.trPePETCCheckButton = wTree.get_widget("trPePETCCheckButton")
        self.trPeApplicationCheckButton = wTree.get_widget("trPeApplicationCheckButton")
        self.trPeAnnualCheckButton = wTree.get_widget("trPeAnnualCheckButton")
        
        self.trPeAssessmentLabel  = wTree.get_widget("trPeAssessmentLabel")
        self.trPePETCLabel  = wTree.get_widget("trPePETCLabel")
        self.trPeApplicationLabel = wTree.get_widget("trPeApplicationLabel")
        self.trPeAnnualLabel = wTree.get_widget("trPeAnnualLabel")
        
        self.trPeTotalLabel = wTree.get_widget("trPeTotalLabel")
        self.trPeOKButton = wTree.get_widget("trPeOKButton")
        
        self.trPeWidgets = \
            [
                [self.trPeAssessmentCheckButton, self.trPeAssessmentLabel],
                [self.trPePETCCheckButton, self.trPePETCLabel],
                [self.trPeApplicationCheckButton, self.trPeApplicationLabel],
                [self.trPeAnnualCheckButton, self.trPeAnnualLabel],
            ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.trPeWidgets:
            
            size_group.add_widget(widget[1])
            
        di = {
            self.trPeAssessmentCheckButton.get_label().replace("_", ""):self.trPeAssessmentLabel,
            self.trPePETCCheckButton.get_label().replace("_", ""):self.trPePETCLabel,
            self.trPeApplicationCheckButton.get_label().replace("_", ""):self.trPeApplicationLabel,
            self.trPeAnnualCheckButton.get_label().replace("_", ""):self.trPeAnnualLabel,
        }
        
        for instance in session.query(Particular).\
            filter(Particular.name=="PETC Fee"):
            
            di[instance.description].set_label(locale.currency(instance.cost, grouping=True))
        
        self.trPeTotal = 0.0
        display_total = "<b>%s</b>" % locale.currency(self.trPeTotal, grouping=True)
        self.trPeTotalLabel.set_label(display_total)
        
        wTree.signal_autoconnect(self)
        
        if DEBUG:
            
            print _("   Creating trPeDialog......... Done")
        
    def create_trDialog(self):
        
        wTree = gtk.glade.XML(self.gladefile, "trDialog")
        
        self.dialog1    = wTree.get_widget("trDialog")
        self.BuCheckbutton = wTree.get_widget("BuCheckbutton")
        self.AcCheckbutton = wTree.get_widget("AcCheckbutton")
        self.PrCheckbutton = wTree.get_widget("PrCheckbutton")
        #self.ReExpander = wTree.get_widget("ReExpander")
        self.FiCheckbutton = wTree.get_widget("FiCheckbutton")
        #self.PeExpander = wTree.get_widget("PeExpander")
        
        wTree.signal_autoconnect(self)
    #***************************************************************************
    # Signal Handlers
    #***************************************************************************
    def on_mainWindow_destroy(self, widget):
        """Called when the application is going to quit"""

        gtk.main_quit()

    def on_aboutDialog_activate(self, widget):

        self.aboutDialog.run()

        #we are done with the dialog, hide it
        self.aboutDialog.hide()

    def on_trCoEntry_key_press_event(self, widget, event):

        if event.hardware_keycode == 13 and self.validate_widgets(self.trWidgets) != -1:
            
            string = self.trCoEntry.get_text()
            
            #self.trCoAlertLabel.set_label("")
            
            try:
                
                particulars = session.query(Particular).filter(Particular.name==string).one()
                
                self.trAddTransaction(string)
                
            except NoResultFound:
                
                return
            
            except MultipleResultsFound:
                
                self.trAddTransaction(string)
                
    def on_trOREntry_key_press_event(self, widget, event):
        
        particulars = session.query(Particular).\
                   filter(Particular.name==self.trCoEntry.get_text())
        
        if event.hardware_keycode == 13 and self.trOREntry.get_text() != "" and \
           particulars.count() != 0:
            
            self.trAddTransaction(self.trCoEntry.get_text())
            
    def on_trBuRadioButton_toggled(self, widget):
        
        widget_list = [self.trBuNewRadioButton, self.trBuRenewalRadioButton]
        
        if widget == widget_list[0]:
            
            w = widget_list[1]
            
        else:
            
            w = widget_list[0]
        
        widget_dict = \
            {
                self.trBuNewRadioButton:self.trBuNewLabel,
                self.trBuRenewalRadioButton:self.trBuRenewalLabel
            }
        
        widget_dict[widget].set_sensitive(True)
        widget_dict[w].set_sensitive(False)
        
        if w.get_label().replace("_", "") in self.trCollectionStringList:
            
            self.trCollectionStringList.remove(w.get_label().replace("_", ""))
            
        if widget.get_label().replace("_", "") not in self.trCollectionStringList:
            
            self.trCollectionStringList.append(widget.get_label().replace("_", ""))
        
    def on_trPrRadioButton_toggled(self, widget):
        
        for w in self.trPrWidgets:
            
            if w[0] is not widget:
                
                w[1].set_sensitive(False)
                
            else:
                
                w[1].set_sensitive(True)
                
                self.PromoTotal = float(w[1].get_label()[3:].replace(",", ""))
                
                display_total = "<b>%s</b>" % locale.currency(self.PromoTotal, grouping=True)
                self.trPrTotalLabel.set_label(display_total)
        
    def on_trReRadioButton_toggled(self, widget):
        
        self.has_surcharge = False
        
        self.trReSurchargeLabel.set_sensitive(False)
        
        for w in self.trReWidgets:
            
            if w[0] is not widget:
                
                if w[1] != self.trReSurchargeLabel or w[0] == self.trReExamRadioButton:
                    
                    w[1].set_sensitive(False)
                    
            else:
                
                self.trReCollection = w[0].get_label().replace("_", "")
                
                self.trReSurchargeLabel.set_label(locale.currency(0.00, grouping=True))
                
                self.trReSurchargeCheckButton.set_sensitive(w[0] != self.trReExamRadioButton)
                
                if w[0] != self.trReExamRadioButton:
                    
                    self.trReSurchargeLabel.set_label(locale.currency(float(w[1].get_label()[3:].replace(",", "")) * .5, grouping=True))
                    
                    if self.trReSurchargeCheckButton.get_active():
                        
                        self.has_surcharge = True
                        self.trReSurchargeLabel.set_sensitive(True)
                        
                
                w[1].set_sensitive(True)
                
                self.trReTotal = float(w[1].get_label()[3:].replace(",", ""))
                
                if self.has_surcharge:
                    
                    self.trReTotal = self.trReTotal + float(w[1].get_label()[3:].replace(",", "")) * .5
                    
                    
                display_total = "<b>%s</b>" % locale.currency(self.trReTotal, grouping=True)
                self.trReTotalLabel.set_label(display_total)
                
    def on_trFiRadioButton_toggled(self, widget):
        
        for w in self.trFiWidgets:
            
            if w[0] is not widget:
                
                w[1].set_sensitive(False)
                
            else:
                
                w[1].set_sensitive(True)
                
                self.trFiTotal = float(w[1].get_label()[3:].replace(",", ""))
                
                display_total = "<b>%s</b>" % locale.currency(self.trFiTotal, grouping=True)
                self.trFiTotalLabel.set_label(display_total)
        
    def on_trDeRadioButton_toggled(self, widget):
        
        for w in self.trDeWidgets:
            
            if w[0] is not widget:
                
                w[1].set_sensitive(False)
                
            else:
                
                self.trDeAccount = w[0].get_label().replace("_", "")
                
                w[1].set_sensitive(True)
                
                self.trDeTotal = float(w[1].get_value())
                
                self.trDeOKButton.set_sensitive(self.trDeTotal != 0.0)
                
                display_total = "<b>%s</b>" % locale.currency(self.trDeTotal, grouping=True)
                self.trDeTotalLabel.set_label(display_total)
                
    def on_trBuRegCheckButton_toggled(self, widget):
        
        self.trBuGeneralTable.set_sensitive(widget.get_active())
        
        if widget.get_active():
            
            self.trBuTotal = self.trBuTotal + 150.0
            
            self.update_trCollectionStringList(True)
            
        else:
            
            self.trBuTotal = self.trBuTotal - 150.0
            
            self.update_trCollectionStringList(False)
            
        display_total = "<b>%s</b>" % locale.currency(self.trBuTotal, grouping=True)
        self.trBuTotalLabel.set_label(display_total)
        
        self.trBuOKButton.set_sensitive(self.trBuTotal != 0.0)
        
    def on_trAcCheckButton_toggled(self, widget):
        
        widget_dict = {
            self.trAcFilingCheckButton:self.trAcFilingLabel,
            self.trAcSurchargeCheckButton:self.trAcSurchargeLabel
        }
        
        widget_dict[widget].set_sensitive(not widget.get_active())
        
        amount = 0
            
        if widget_dict[widget].get_label()[3:] == "0.00":
                
            amount = float(self.trAcStarLabel.get_label()[3:].replace(",", ""))
            amount = amount * .5
                
        else:
                
            amount = float(widget_dict[widget].get_label()[3:].replace(",", ""))
        
        if widget.get_active():
            
            self.AccredTotal = self.AccredTotal + amount
            
        else:
            
            self.AccredTotal = self.AccredTotal - amount
            
        display_total = "<b>%s</b>" % locale.currency(self.AccredTotal, grouping=True)
        self.trAcTotalLabel.set_label(display_total)
            
    def on_trBuCheckButton_toggled(self, widget):
        
        widget_dict = {
            self.trBuDocStampsCheckButton:self.trBuDocStampsLabel,
            self.trBuSurchargeCheckButton:self.trBuSurchargeLabel,
            self.trBuCertificationCheckButton:self.trBuCertificationLabel,
            self.trBuChangeOfBNCheckButton:self.trBuChangeOfBNLabel,
            self.trBuBulkCheckButton:self.trBuBulkLabel,
        }
        
        widget_dict[widget].set_sensitive(widget.get_active())
        
        string = widget.get_label().replace("_", "")
        amount = widget_dict[widget].get_label()[3:]
        
        if widget.get_active():

            
            self.trBuTotal = self.trBuTotal + float(amount)
            
            if string not in self.trCollectionStringList:
                
                self.trCollectionStringList.append(string)
                
        else:
            
            self.trBuTotal = self.trBuTotal - float(amount)
            
            if string in self.trCollectionStringList:
                
                self.trCollectionStringList.remove(string)
            
                
        display_total = "<b>%s</b>" % locale.currency(self.trBuTotal, grouping=True)
        self.trBuTotalLabel.set_label(display_total)
            
        self.trBuOKButton.set_sensitive(self.trBuTotal != 0.0)
        
    def on_trPeCheckButton_toggled(self, widget):
        
        di = {
            self.trPeAssessmentCheckButton.get_label().replace("_", ""):self.trPeAssessmentLabel,
            self.trPePETCCheckButton.get_label().replace("_", ""):self.trPePETCLabel,
            self.trPeApplicationCheckButton.get_label().replace("_", ""):self.trPeApplicationLabel,
            self.trPeAnnualCheckButton.get_label().replace("_", ""):self.trPeAnnualLabel,
        }
        
        widget_dict = {
            self.trPeAssessmentCheckButton:self.trPeAssessmentLabel,
            self.trPePETCCheckButton:self.trPePETCLabel,
            self.trPeApplicationCheckButton:self.trPeApplicationLabel,
            self.trPeAnnualCheckButton:self.trPeAnnualLabel,
        }
        
        widget_dict[widget].set_sensitive(widget.get_active())
        
        string = widget.get_label().replace("_", "")
        amount = widget_dict[widget].get_label()[3:].replace(",", "")
        
        if widget.get_active():
            
            self.trPeTotal = self.trPeTotal + float(amount)
            
        else:
            
            self.trPeTotal = self.trPeTotal - float(amount)
            
        display_total = "<b>%s</b>" % locale.currency(self.trPeTotal, grouping=True)
        self.trPeTotalLabel.set_label(display_total)
            
        self.trPeOKButton.set_sensitive(self.trPeTotal != 0.0)
        
    def on_trReSurchargeCheckButton_toggled(self, widget):
        
        self.trReSurchargeLabel.set_sensitive(widget.get_active())
        
        if widget.get_active():
            
            self.trReTotal = self.trReTotal + float(self.trReSurchargeLabel.get_label()[3:].replace(",", ""))
            self.has_surcharge = True
            
        else:
            
            self.trReTotal = self.trReTotal - float(self.trReSurchargeLabel.get_label()[3:].replace(",", ""))
            self.has_surcharge = False
            
        display_total = "<b>%s</b>" % locale.currency(self.trReTotal, grouping=True)
        self.trReTotalLabel.set_label(display_total)
        
    def on_trAcStarCombobox_changed(self, widget):
        
        starModel = self.trAcStarCombobox.get_model()
        starActive = self.trAcStarCombobox.get_active()
        
        star = starModel[starActive][0]
        
        p = session.query(Particular).filter(Particular.name=="Accreditation Fee").\
          filter(Particular.description==star).one()
        
        self.trAcStarLabel.set_label(locale.currency(p.cost, grouping=True))
        
        self.trAcSurchargeLabel.set_label(locale.currency(p.cost * .5, grouping=True))
        
        amount = p.cost + 0.0
        
        if self.trAcFilingCheckButton.get_active():
            
            amount = amount + float(self.trAcFilingLabel.get_label()[3:].replace(",", ""))
            
        if self.trAcSurchargeCheckButton.get_active():
            
            amount = amount + float(self.trAcSurchargeLabel.get_label()[3:].replace(",", ""))
            
        self.AccredTotal = amount
        
        display_total = "<b>%s</b>" % locale.currency(self.AccredTotal, grouping=True)
        self.trAcTotalLabel.set_label(display_total)
        
    def on_trDeSpinbutton_value_changed(self, widget):
        
        self.trDeTotal = float(widget.get_value())
                
        display_total = "<b>%s</b>" % locale.currency(self.trDeTotal, grouping=True)
        self.trDeTotalLabel.set_label(display_total)
        
    def on_reFindPrintButton_clicked(self, widget):
        
        model = self.reFilterCombobox.get_model()
        active = self.reFilterCombobox.get_active()
        
        if model[active][0] == _("Commission on Audit"):
            
            if widget.get_label() == "gtk-find":
                
                self.reCOADisplayReport()
                
            elif widget.get_label() == "gtk-print":
                
                self.reCOAPrintReport()
            
        elif model[active][0] == _("Bureau of Internal Revenue"):
            
            self.reBIRDisplayReport()
            
        elif model[active][0] == _("Department of Trade and Industry"):
            
            self.reDTIDisplayReport()
        
    def on_trButton_clicked(self, widget):

        self.notebook.set_current_page(0)
        self.trPayorEntry.grab_focus()

    def on_reButton_clicked(self, widget):
        
        self.notebook.set_current_page(1)
        self.on_reFindPrintButton_clicked(self.reFindButton)
        
    def on_maButton_clicked(self, widget):

        #self.notebook.set_current_page(2)
        
        self.maintenanceDialog.run()
        self.maintenanceDialog.hide()
        #self.reNotebook.set_current_page(0)

    def on_trCheckbutton_toggled(self, widget):
        
        di = {self.BuCheckbutton:self.trBuDialog, self.AcCheckbutton:self.trAcDialog, 
              self.PrCheckbutton:self.trPrDialog, self.FiCheckbutton:self.trFiDialog}
        
        if widget.get_active() == True:
            di[widget].run()
            di[widget].hide()
                
    def on_daButton_clicked(self, widget):

        self.notebook.set_current_page(3)
        
        self.dialog1.run()
        self.dialog1.hide()
        

    def on_maTreeview_cursor_changed(self, widget):
        
        model = widget.get_model()
        
        selected_row = widget.get_selection().get_selected_rows()
        
        _iter = model.get_iter(selected_row[1][0])
        
        di = {"General":0, "Particular":1, "User Account":2}
        
        self.maNotebook.set_current_page(di[model[_iter][0]])
        
    #***************************************************************************
    # Custom Functions
    #***************************************************************************
    def draw_page_template(self, context, page, total_pages, li, header_dict):
        
        global count
        
        cnt  = -1
        flag = 0
        
        if count > 30:
            
            flag = 30
            
        else:
            
            flag = count
            
        print count
        
        cr = context.get_cairo_context()
        
        date_printed = "Printed on " + str(datetime.date.today())
        page_number  = "Page " + str(page+1) + " of " + str(total_pages)
        signature    = "Created using bT"
        
        layout = context.create_pango_layout()
        layout.set_markup(page_number + "\n" + date_printed + "\n" + signature)
        layout.set_font_description(pango.FontDescription("sans 6"))
        layout.set_alignment(pango.ALIGN_RIGHT)
        
        cr.move_to(context.get_width()- layout.get_pixel_size()[0], 0)
        cr.layout_path(layout)
        
        ## Draw some text
        header = "<span font_desc=\"Sans Italic 12\"><b>" + "\n" + \
               "CASH RECEIPTS RECORD</b></span>"          + "\n" + \
               "Department of Trade and Industry"         + "\n" + \
               "Negros Oriental Provincial Office"        + "\n" + \
               "Dumaguete City"
        
        layout = context.create_pango_layout()
        layout.set_markup(header)
        layout.set_font_description(pango.FontDescription("sans 10"))
        layout.set_alignment(pango.ALIGN_CENTER)
        
        w, h = layout.get_pixel_size()
        cr.move_to(context.get_width() / 2 - (w / 2), 0)
        cr.layout_path(layout)
        
        for l in li:
            
            layout = context.create_pango_layout()
            layout.set_markup(l[0])
            layout.set_font_description(pango.FontDescription("sans 10"))
            
            cr.move_to(header_dict[l[0]], 25.5)
            cr.layout_path(layout)
    
        ## Font Fill
        cr.set_source_rgb(0, 0, 0)
        cr.fill()
        
        idx = 25 ## Draw some horizontal lines
        while cnt != flag + 1:
            
            cr.move_to(0, idx)
            cr.line_to(context.get_width(), idx)
            
            cr.set_source_rgb(0, 0, 0)
            cr.set_line_width(.1)
            
            cr.stroke()
            
            idx += 5
            cnt += 1
        
        for l in li:
            
            cr.move_to(l[1]-2, 25)
            cr.line_to(l[1]-2, idx)
            
            cr.set_source_rgb(0, 0, 0)
            cr.set_line_width(.1)
            
            cr.stroke()
            
        cr.rectangle(0, 25, context.get_width(), idx-25)
        cr.rectangle(0, 25, context.get_width(), 5)
      
        cr.set_source_rgb(0, 0, 0)
        cr.set_line_width(.1)
        
        cr.stroke()
        
        layout = context.create_pango_layout()
        layout.set_markup("<b>TOTAL</b>")
        layout.set_font_description(pango.FontDescription("sans 10"))
        layout.set_alignment(pango.ALIGN_CENTER)
        
        cr.move_to(200, idx-4.5)
        cr.layout_path(layout)
        
    def draw_coa_page (self, operation, context, page_nr, pages, dates):
        
        global count, total_undeposited, current_date
        total_collected = 0
        total_deposited = 0
        
        cr = context.get_cairo_context()
        
        li = [
            ["<b>Date</b>", 2], ["<b>OR / DS #</b>", 25], ["<b>Name of Payor</b>", 50],
            ["<b>Nature of Collection</b>", 110], ["<b>Collection</b>", 215],
            ["<b>Deposit</b>", 245], ["<b>Undeposited Collection</b>", 275],
        ]
        
        header_dict = {
            "<b>Date</b>":8, "<b>OR / DS #</b>":27.5, "<b>Name of Payor</b>":61, 
            "<b>Nature of Collection</b>":145, "<b>Collection</b>":220,
            "<b>Deposit</b>":252, "<b>Undeposited Collection</b>":275,
        }
        
        self.draw_page_template(context, page_nr, pages, li, header_dict)
        
        count -= 30
        
        idx = 30.5 ## Draw data to page
        for instance in session.query(Transaction).filter(Transaction.date >= dates[0]).\
            filter(Transaction.date <= dates[1])[page_nr*30:(page_nr*30)+30]:
            
            inst = [instance.date, instance.or_number, instance.payor, instance.nature, instance.amount]
            
            i = 0
            for l in li[0:5]:
                
                layout = context.create_pango_layout()
                layout.set_font_description(pango.FontDescription("sans 10"))
                
                if i == 0:
                    
                    if current_date == instance.date:
                        
                        pass
                    
                    else:
                        
                        current_date = instance.date
                        
                        layout.set_text(str(inst[i]))
                        cr.move_to(l[1], idx)
                        layout.set_alignment(pango.ALIGN_CENTER)
                        
                        cr.layout_path(layout)
                        
                ## OR / DS #
                elif i == 1:
                    
                    layout.set_text(str(inst[i]))
                    
                    w, h = layout.get_pixel_size()
                    
                    cr.move_to(li[2][1] - 4 - w, idx)
                    layout.set_alignment(pango.ALIGN_RIGHT)
                    
                    cr.layout_path(layout)
                    
                ## Collections or Deposits
                elif i == 4:
                    
                    string = locale.currency(float(inst[i]), grouping=True)
                    
                    ## 0 : collection 1 : deposite
                    di = {
                        0:[string, " - ", total_undeposited + float(inst[i])], 
                        1:[" - ", string, total_undeposited - float(inst[i])], 
                    }
                    
                    if instance.t_type == 0:
                        
                        total_collected += float(inst[i])
                        
                    else:
                        
                        total_deposited += float(inst[i])
                    
                    layout.set_text(di[instance.t_type][0])
                    
                    total_undeposited = di[instance.t_type][2]
                    
                    w, h = layout.get_pixel_size()
                    
                    cr.move_to(li[5][1] - 4 - w, idx)
                    layout.set_alignment(pango.ALIGN_RIGHT)
                    
                    cr.layout_path(layout)
                    
                    layout = context.create_pango_layout()
                    layout.set_text(di[instance.t_type][1])
                    layout.set_font_description(pango.FontDescription("sans 10"))
                    
                    cr.move_to(li[6][1] - 4 - layout.get_pixel_size()[0], idx)
                    layout.set_alignment(pango.ALIGN_RIGHT)
                    
                    cr.layout_path(layout)
                    
                else:
                    
                    layout.set_text(str(inst[i]))
                    cr.move_to(l[1], idx)
                    layout.set_alignment(pango.ALIGN_CENTER)
                    
                    cr.layout_path(layout)
                    
                i += 1
                
            ## [begin] Display undeposited collection
            layout = context.create_pango_layout()
            layout.set_font_description(pango.FontDescription("sans 10"))
            
            if total_undeposited != 0.0:
                
                layout.set_text(locale.currency(total_undeposited, grouping=True))
                
            else:
                
                layout.set_text(" - ")
            
            w, h = layout.get_pixel_size()
            
            cr.move_to(320 - 4 - w, idx)
            cr.layout_path(layout)
            ## [ end ] Display undeposited collection
            
            idx += 5
            
        self.draw_coa_page_total(operation, context, idx, li, total_collected, total_deposited)
        
    def draw_coa_page_total(self, operation, context, idx, li, total_collected, total_deposited):
        
        global total_undeposited
        
        cr = context.get_cairo_context()
        
        ## [begin] Display total collected
        layout = context.create_pango_layout()
        layout.set_font_description(pango.FontDescription("sans 10"))
        
        if total_collected != 0.0:
            
            amount = locale.currency(total_collected, grouping=True)
            
            layout.set_markup("<b>%s</b>" % amount)
            
        else:
            
            layout.set_markup("<b> - </b>")
        
        w, h = layout.get_pixel_size()
        
        cr.move_to(li[5][1] - 4 - w, idx)
        layout.set_alignment(pango.ALIGN_RIGHT)
        
        cr.layout_path(layout)
        ## [ end ] Display total collected
        
        ## [begin] Display total deposited
        layout = context.create_pango_layout()
        layout.set_font_description(pango.FontDescription("sans 10"))
        
        if total_deposited != 0.0:
            
            amount = locale.currency(total_deposited, grouping=True)
            
            layout.set_markup("<b>%s</b>" % amount)
            
        else:
            
            layout.set_markup("<b> - </b>")
        
        w, h = layout.get_pixel_size()
        
        cr.move_to(li[6][1] - 4 - w, idx)
        layout.set_alignment(pango.ALIGN_RIGHT)
        
        cr.layout_path(layout)
        ## [ end ] Display total deposited
        
        ## [begin] Display total undeposited
        layout = context.create_pango_layout()
        layout.set_font_description(pango.FontDescription("sans 10"))
        
        if total_undeposited != 0.0:
            
            amount = locale.currency(total_undeposited, grouping=True)
            
            layout.set_markup("<b>%s</b>" % amount)
            
        else:
            
            layout.set_markup("<b> - </b>")
        
        w, h = layout.get_pixel_size()
        
        cr.move_to(320 - 4 - w, idx)
        layout.set_alignment(pango.ALIGN_RIGHT)
        
        cr.layout_path(layout)
        ## [ end ] Display total undeposited
        
        cr.set_source_rgb(0, 0, 0)
        cr.fill()
        
    def request_page_setup(self, operation, context, page_nr, page_setup):
        
        paper_size = gtk.paper_size_new_custom("Folio [8.5in x 13in]", 
            "Folio [8.5in x 13in]", 216, 330, gtk.UNIT_MM)
        page_setup.set_orientation(gtk.PAGE_ORIENTATION_LANDSCAPE)
        page_setup.set_paper_size(paper_size)
        
    def reset_widgets(self, widgetsList, value=True, notebook=None):
        
        idx = 0
        for w in widgetsList:
            
            if idx == 0:
                
                w[0].grab_focus()
                idx = idx + 1
                
            widget = w[0]
            label  = w[1]
            text   = w[2]

            if notebook:

                notebook.set_current_page(0)

            label.set_markup_with_mnemonic("%s" % text)
            widget.set_sensitive(True)

            if value:

                if type(widget) == gtk.Entry:

                    widget.set_text("")

                elif type(widget) == gtk.ComboBox:

                    widget.set_active(0)

                elif type(widget) == gtk.TreeView:

                    model = widget.get_model()
                    model.clear()

                    entries = {
                        "inGenresAddEditListstore"  : self.inGenresEntry,
                        "inCastsAddEditListstore"   : self.inCastsEntry,
                        "inWritersAddEditListstore" : self.inWritersEntry
                    }

                    entry = entries[model.get_name()]

                    if entry:

                        entry.set_text("")

                    widget.get_selection().unselect_all()

                elif type(widget) == gtk.SpinButton:

                    widget.set_value(0.0)

    def validate_widgets(self, widgetsList, notebook=None):

        """Validates all the widgets from the widgetList for possible errors."""

        types = (gtk.Entry, gtk.ComboBox, gtk.TreeView, gtk.SpinButton)

        ret_value = 0

        for w in widgetsList:

            widget = w[0]
            label  = w[1]
            text   = w[2]

            if notebook:

                notebook.set_current_page(w[3])

            if type(widget) == types[0]:

                if widget.get_text() == "":

                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)

                    widget.grab_focus()

                    ret_value = -1

                    break

                else:

                    label.set_markup_with_mnemonic("%s" % text)

            elif type(widget) == types[1]:

                model = widget.get_model()
                active = widget.get_active()

                if model[active][0] == _('Select one'):

                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)

                    widget.grab_focus()

                    ret_value = -1

                    break

                else:

                    label.set_markup_with_mnemonic("%s" % text)

            elif type(widget) == types[2]:

                entries = {
                    "inGenresAddEditListstore"  : self.inGenresEntry,
                    "inCastsAddEditListstore"   : self.inCastsEntry,
                    "inWritersAddEditListstore" : self.inWritersEntry
                }

                model = widget.get_model()

                if len(model) == 0:

                    entry = entries[model.get_name()]

                    if entry:

                        entry.grab_focus()

                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)

                    ret_value = -1

                    break

                else:

                    label.set_markup_with_mnemonic("%s" % text)

            elif type(widget) == types[3]:

                if widget.get_value() == 0.0:

                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)

                    widget.grab_focus()

                    ret_value = -1

                    break

                else:

                    label.set_markup_with_mnemonic("%s" % text)

        return ret_value

    def in_movie_list(self, movie, liststore):

        """Checks if the movie object is in the liststore."""

        _iter = liststore.get_iter_first()
        return_val = False

        self.reInAlertLabel.set_label("")

        while _iter != None:

            m = liststore.get_value(_iter, 0)

            if m != movie:

                pass

            elif m == movie:

                return_val = True
                self.reInAlertLabel.set_label("<span foreground='red'>%s is already in the list.</span>" % m.title)

            elif m.status != 2:

                return_val = True

            elif m.status == 2:

                return_val = True
                self.reInAlertLabel.set_label("<span foreground='red'>%s has already been rented.</span>" % m.title)

            _iter = liststore.iter_next(_iter)

        return return_val

    def trAddTransaction(self, string):
        
        self.trCollectionStringList = []
        itemList = []
        result = None
        t_type = None
        
        if   string == "BN Registration":
            
            t_type = 0
            
            self.trCollectionStringList.append("New")
            self.trCollectionStringList.append("Documentary Stamps")
            
            self.BuExpander.activate()
            result = self.trBuDialog.run()
            
            self.trBuDialog.hide()
            
            if result == gtk.RESPONSE_OK:
                
                n = ""
                if "New" in self.trCollectionStringList:
                    
                    n = "BN Registration (N)"
                    itemList.append(
                        Item(
                            "BN Registration (N)",
                            float(self.trBuNewLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                elif "Renewal" in self.trCollectionStringList:
                    
                    n = "BN Registration (R)"
                    itemList.append(
                        Item(
                            "BN Registration (R)",
                            float(self.trBuNewLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                if "Documentary Stamps" in self.trCollectionStringList:
                    
                    if n != "":
                        
                        n = n + " | " + self.trBuDocStampsCheckButton.get_label().replace("_", "")
                        
                    else:
                        
                        n = self.trBuDocStampsCheckButton.get_label().replace("_", "")
                        
                    itemList.append(
                        Item(
                            self.trBuDocStampsCheckButton.get_label().replace("_", ""),
                            float(self.trBuDocStampsLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                if "Surcharge Fees" in self.trCollectionStringList:
                    
                    if n != "":
                        
                        n = n + " | " + self.trBuSurchargeCheckButton.get_label().replace("_", "")
                        
                    else:
                        
                        n = self.trBuSurchargeCheckButton.get_label().replace("_", "")
                        
                    itemList.append(
                        Item(
                            self.trBuSurchargeCheckButton.get_label().replace("_", ""),
                            float(self.trBuSurchargeLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                if "Bulk Sales" in self.trCollectionStringList:
                    
                    if n != "":
                        
                        n = n + " | " + self.trBuBulkCheckButton.get_label().replace("_", "")
                        
                    else:
                        
                        n = self.trBuBulkCheckButton.get_label().replace("_", "")
                        
                    itemList.append(
                        Item(
                            self.trBuBulkCheckButton.get_label().replace("_", ""),
                            float(self.trBuBulkLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                if "Change of Business Name" in self.trCollectionStringList:
                    
                    if n != "":
                        
                        n = n + " | " + self.trBuChangeOfBNCheckButton.get_label().replace("_", "")
                        
                    else:
                        
                        n = self.trBuChangeOfBNCheckButton.get_label().replace("_", "")
                        
                    itemList.append(
                        Item(
                            self.trBuChangeOfBNCheckButton.get_label().replace("_", ""),
                            float(self.trBuChangeOfBNLabel.get_label()[3:].replace(",", ""))
                        ))
                    
                a = str(float(self.trBuTotal))
                
            self.reset_trBuDialog()
            
        elif string == "Accreditation Fee":
            
            t_type = 0
            
            self.AcExpander.activate()
            result = self.trAcDialog.run()
            
            self.trAcDialog.hide()
            
            if result == gtk.RESPONSE_OK:
                
                starModel = self.trAcStarCombobox.get_model()
                starActive = self.trAcStarCombobox.get_active()
                
                star = starModel[starActive][0]
                n = "Accreditation Fee (%s)" % star
                
                if self.trAcFilingCheckButton.get_active():
                    
                    n = n + " | " + "Filing Fees"
                    
                if self.trAcSurchargeCheckButton.get_active():
                    
                    n = n + " | " + "Surcharge Fees"
                    
                a = str(float(self.AccredTotal))
                
                itemList.append(Item("Accreditation Fee", float(a)))
                
        elif string == "Sales Promo":
            
            t_type = 0
            
            self.PrExpander.activate()
            result = self.trPrDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                n = "Sales Promo"
                a = str(self.PromoTotal)
                itemList.append(Item(n, float(a)))
                
            self.trPrDialog.hide()
            
        elif string == "Real Estate":
            
            t_type = 0
            
            self.ReExpander.activate()
            result = self.trReDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                n = "Real Estate Fee (%s)" % self.trReCollection
                
                if self.has_surcharge:
                    
                    n = n + " | " + "Surcharge Fees"
                    
                    self.has_surcharge = False
                    
                a = str(float(self.trReTotal))
                itemList.append(Item("Real Estate Fee", float(a)))
            
            self.trReDialog.hide()
            
        elif string == "Fire Extinguisher":
            
            t_type = 0
            
            self.FiExpander.activate()
            result = self.trFiDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                n = "Fire Extinguisher"
                
                a = str(float(self.trFiTotal))
                itemList.append(Item("Fire Extinguisher Fee", float(a)))
            
            self.trFiDialog.hide()
            
        elif string == "PETC Fee":
            
            t_type = 0
            
            self.PeExpander.activate()
            result = self.trPeDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                n = "PETC Fee"
                
                a = str(float(self.trPeTotal))
                itemList.append(Item("PETC Fee", float(a)))
            
            self.trPeDialog.hide()
            
        elif string == "Deposit":
            
            t_type = 1
            
            result = self.trDeDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                n = "Deposit [%s]" % self.trDeAccount
                
                a = str(float(self.trDeTotal))
                itemList.append(Item(self.trDeAccount, float(a)))
                
            self.trDeDialog.hide()
            self.trDeBIRSpinbutton.set_value(0.0)
            self.trDeDTISpinbutton.set_value(0.0)
            self.on_trDeRadioButton_toggled(self.trDeDTIRadioButton)
            
        if result == gtk.RESPONSE_OK:
            
            o       = self.trOREntry.get_text()
            d       = self.trDateCalendar.get_date()
            p       = self.trPayorEntry.get_text()
            t       = Transaction(o, str(d), p, n, t_type, a)
            t.items = itemList
            
            l = Log(str(datetime.datetime.today()), "Added : " + str(t))
            l.user_id = self.current_user.id
            
            session.add(t)
            session.add(l)
            session.commit()
            
            self.update_trCoListstore([t])
            
        self.reset_widgets(self.trWidgets)
        
    def reCOADisplayReport(self):
        
        self.reCOAListstore.clear()
        
        fromDate = self.reFromDateCalendar.get_date()
        toDate   = self.reToDateCalendar.get_date()
        
        self.update_reCOAListstore(str(fromDate), str(toDate))
        
    def reCOAPrintReport(self):
        
        global count, total_undeposited, current_date
        
        count = 0
        total_undeposited = 0.0
        
        fromDate = str(self.reFromDateCalendar.get_date())
        toDate   = str(self.reToDateCalendar.get_date())
        
        print_ = gtk.PrintOperation()
        
        count = session.query(Transaction).filter(Transaction.date >= fromDate).\
              filter(Transaction.date <= toDate).count()
        
        if count / 30 < 1:
            
            pages = 1
            
        else:
            
            pages = (count / 30) + 1
            
            
        print_.set_n_pages(pages)
        print_.set_unit(gtk.UNIT_MM)
        print_.set_export_filename("test.pdf")
        print_.connect("draw_page", self.draw_coa_page, pages, [fromDate, toDate])
        print_.connect("request_page_setup", self.request_page_setup)
        res = print_.run(gtk.PRINT_OPERATION_ACTION_PRINT)
    def reBIRDisplayReport(self):
        
        print "BIR"
        
        print self.reFromDateCalendar.get_text()
        print self.reToDateCalendar.get_text()
        
    def reDTIDisplayReport(self):
        
        print "DTI"
        
        print self.reFromDateCalendar.get_text()
        print self.reToDateCalendar.get_text()
        
    def reset_trBuDialog(self):
        
        self.trBuNewRadioButton.set_active(True)
        self.trBuRegCheckButton.set_active(True)
        self.on_trBuRegCheckButton_toggled(self.trBuRegCheckButton)
        
        widget_list = \
            [
                self.trBuDocStampsCheckButton, self.trBuSurchargeCheckButton,
                self.trBuCertificationCheckButton, self.trBuChangeOfBNCheckButton,
                self.trBuBulkCheckButton,
            ]
        
        if self.trBuDocStampsCheckButton.get_active() == False:
            
            self.trBuDocStampsCheckButton.set_active(True)
            
        if self.trBuSurchargeCheckButton.get_active() == True:
            
            self.trBuSurchargeCheckButton.set_active(False)
            
        if self.trBuBulkCheckButton.get_active() == True:
            
            self.trBuBulkCheckButton.set_active(False)
            
        if self.trBuCertificationCheckButton.get_active() == True:
            
            self.trBuCertificationCheckButton.set_active(False)
            
        if self.trBuChangeOfBNCheckButton.get_active() == True:
            
            self.trBuChangeOfBNCheckButton.set_active(False)
            
        self.on_trBuRadioButton_toggled(self.trBuNewRadioButton)
        
        self.on_trBuCheckButton_toggled(self.trBuDocStampsCheckButton)
        self.on_trBuCheckButton_toggled(self.trBuSurchargeCheckButton)
        self.on_trBuCheckButton_toggled(self.trBuBulkCheckButton)
        self.on_trBuCheckButton_toggled(self.trBuCertificationCheckButton)
        self.on_trBuCheckButton_toggled(self.trBuChangeOfBNCheckButton)
        
        self.trBuTotal = 0.0
        for instance in session.query(Particular).\
            filter(Particular.name=="BN Registration"):
            
            if instance.description == "New" or instance.description == "Documentary Stamps":
                
                self.trBuTotal  += instance.cost
                
        display_total = "<b>%s</b>" % locale.currency(self.trBuTotal, grouping=True)
        self.trBuTotalLabel.set_label(display_total)
        
    def update_trCoListstore(self, trList):
        
        for instance in trList:
            
            trans = []
            
            trans.append(instance)
            trans.append(instance.id)
            trans.append(instance.date)
            trans.append(instance.or_number)
            trans.append(instance.payor)
            trans.append(instance.nature)
            trans.append(locale.currency(float(instance.amount), grouping=True))
            
            self.trCoListstore.append(trans)
            
    def update_reCOAListstore(self, fromDate, toDate):
        
        for instance in session.query(Transaction).filter(Transaction.date >= fromDate).\
            filter(Transaction.date <= toDate):
            
            trans = []
            
            trans.append(instance)
            trans.append(instance.id)
            trans.append(instance.date)
            trans.append(instance.or_number)
            trans.append(instance.payor)
            trans.append(instance.nature)
            trans.append(locale.currency(float(instance.amount), grouping=True))
            
            self.reCOAListstore.append(trans)

    def update_trCollectionStringList(self, is_active):
        
        new = "New"
        ren = "Renewal"
        
        li = [new, ren]
        
        if is_active:
            
            if self.trBuNewRadioButton.get_active() and \
               new not in self.trCollectionStringList:
                
                self.trCollectionStringList.append(new)
                
            else:
                
                if ren not in self.trCollectionStringList:
                    
                    self.trCollectionStringList.append(ren)
                    
        else:
            
            for l in li:
                
                if l in self.trCollectionStringList:
                    
                    self.trCollectionStringList.remove(l)
                    
    def populate_trListstore(self):
        
        for instance in session.query(Transaction):
            
            trans = []
            
            trans.append(instance)
            trans.append(instance.id)
            trans.append(instance.date)
            trans.append(instance.or_number)
            trans.append(instance.payor)
            trans.append(instance.nature)
            trans.append(locale.currency(float(instance.amount), grouping=True))
            
            self.trCoListstore.append(trans)
            
    def populate_maListstore(self):
        
        li = [_("General"), _("Particular"), _("User Account")]
        
        idx = 1
        for item in li:
            
            it = []
            it.append(item)
            it.append(idx)
            it.append(item)
            
            self.maListstore.append(it)
            idx += 1
            
    def add_image(self, parent, filename, text):

        box1 = gtk.VBox(False, 0)
        box1.set_border_width(2)

        image = gtk.Image()
        image.set_from_file(os.path.join(self.local_path, "img", filename))

        label = gtk.Label()
        label.set_text_with_mnemonic(text)

        box1.pack_start(image, False, False, 3)
        box1.pack_start(label, False, False, 3)

        image.show()
        label.show()

        return box1

    def show_loginDialog(self):
        
        ret_value = -1
        self.current_user = None
        
        wTree = gtk.glade.XML(self.gladefile, "loginDialog")
        
        self.loginDialog     = wTree.get_widget("loginDialog")
        
        self.loUsernameEntry = wTree.get_widget("loUsernameEntry")
        self.loPasswordEntry = wTree.get_widget("loPasswordEntry")
        
        self.loUsernameLabel = wTree.get_widget("loUsernameLabel")
        self.loPasswordLabel = wTree.get_widget("loPasswordLabel")
        
        self.loWidgets = \
        [
            [self.loUsernameEntry, self.loUsernameLabel, _("_Username:")],
            [self.loPasswordEntry, self.loPasswordLabel, _("_Password:")],
        ]
        
        self.loUsernameEntry.set_activates_default(True)
        self.loPasswordEntry.set_activates_default(True)
        
        result = self.loginDialog.run()
        
        while result == gtk.RESPONSE_OK and self.validate_widgets(self.loWidgets) == -1:
            
            result = self.loginDialog.run()
            
            self.reset_widgets(self.loWidgets, False)
            
        if (result == gtk.RESPONSE_OK):
            
            username = self.loUsernameEntry.get_text()
            password = self.loPasswordEntry.get_text()
            
            u = User(username, password)
            
            try:
                user = session.query(User).filter(User.username==username).one()
                
                if u.password == user.password:
                    
                    self.current_user = user
                    
                    ret_value = 0
                    
            except NoResultFound:
                
                pass
            
        elif (result == gtk.RESPONSE_CANCEL or result == gtk.RESPONSE_DELETE_EVENT):
            
            ret_value = 1
            
        self.loginDialog.hide()
        
        return ret_value
    
    def set_cursor(self, value):
        
        cursor_dict = {"watch":gtk.gdk.WATCH}
        
        cursor = gtk.gdk.Cursor(cursor_dict[value])
        
        self.root_window.set_cursor(cursor)
        
    def set_permissions(self):
        
        self.statusbar.push(self.context_id, _("Welcome to %s %s  ||  user: %s") \
            % (APP_NAME, __appversion__, self.current_user.username))
        
        self.current_permissions = self.current_user.get_permissions()
        
        di = \
        {
            'view_transaction':self.trButton, 'view_report':self.reButton,
            'print_report':self.rePrintButton, 'view_maintenance':self.maButton,
        }
        
        for k in di.keys():
            
            di[k].set_sensitive(self.current_permissions[k])
            
    def security(self):
        
        tries = 3
        
        while tries != 0:
            
            ret_value = self.show_loginDialog()
            
            if ret_value != 0 and ret_value != 1:
                
                tries -= 1
                
            elif ret_value == 1:
                
                sys.exit(0)
                
            else:
                
                break
            
        if ret_value != 0:
            
            sys.exit(1)

def display_doc_stamps():
    
    for instance in session.query(Item).filter(Item.name=="Documentary Stamps"):
        
        print instance.transactions[0].or_number, instance.transactions[0].payor, instance.name, instance.amount

if __name__ == "__main__":
    
    for instance in session.query(Log):
        
        print instance.date_time, instance.user.username, instance.description
    
    colrecsys = ColRecSys()
    
    gtk.main()
    